package com.beikai.redisdemo.controller;

import com.alibaba.fastjson.JSONObject;
import com.beikai.redisdemo.model.User;
import com.beikai.redisdemo.service.IUserService;
import com.beikai.redisdemo.utils.Profile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;

/**
 * Created with IntelliJ IDEA.
 *
 * @author : hanbeikai
 * Date: 2021/5/3 10:45 下午
 * Description: No Description
 */
@RequestMapping("/user")
@RestController
@Slf4j
public class UserController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate<String, Serializable> redisCacheTemplate;
    @Autowired
    private IUserService userService;

    @RequestMapping("/test")
    public void test() {
        redisCacheTemplate.opsForValue().set("userkey", new User("张三",1L, 25));
        User user = (User) redisCacheTemplate.opsForValue().get("userkey");
        log.info("当前获取对象：{}", user.toString());
    }

    @PostMapping("/add")
    public JSONObject add(@RequestBody User vo) {
        log.info("添加的用户信息：{}",vo.toString());
        User user = userService.save(vo);
        return getResult(user);
    }
    @DeleteMapping("/delete/{id}")
    public JSONObject delete(@PathVariable("id") Long id) {
        userService.delete(id);
        return getResult(true);
    }
    @GetMapping("/get/{id}")
    public JSONObject get(@PathVariable("id") Long idStr) throws Exception{
        if (null == idStr) {
            throw new Exception("id为空");
        }
        User user = userService.get(idStr);
        log.info("获取的用户信息：{}",JSONObject.toJSONString(user));
        return getResult(user);
    }

    private JSONObject getResult(Object data){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",100);
        jsonObject.put("data",data);
        return jsonObject;
    }

    @Autowired
    private Profile profile;

    @GetMapping("/getProfile")
    public JSONObject getProfile(){
        return getResult(profile.getEnv());
    }

    @Autowired
    private Environment environment;

    @GetMapping("/getProfile2")
    public JSONObject getProfile2(){
        return getResult(environment.getActiveProfiles()[0]);
    }

    @GetMapping("/testTrans")
    public JSONObject testTrans(){
        return getResult(userService.testTrans());
    }
}
